<template>
  <Transition name="slide-up">
    <div v-if="audioStore.isDetailShow" class="custom-drawer" :style="{
      background: `linear-gradient(135deg, 
                         ${backgroundColor} 0%, 
                         ${backgroundColor} 100%)`
    }">
      <div class="close-btn" @click="closeDrawer">
        <el-icon size="24">
          <Close />
        </el-icon>
      </div>
      <div class="main">
        <div class="left">
          <div class="img-container">
            <img ref="imgRef" :src="`${config.downloadUrl}?name=${audioStore.pic}`" @load="handleImageLoad" :class="{ 'rotating': audioStore.isPlay }"
              crossorigin="anonymous">
          </div>
          <span class="song-title">{{ audioStore.title }}</span>
          <span class="artist-name">{{ audioStore.artist }}</span>
          <div class="control-buttons">
            <!-- 上一首 -->
            <svg @click="prev()" style=" margin-left: 50px;" t="1731721064658" class="icon" viewBox="0 0 1024 1024"
              version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4592" width="200" height="200">
              <path
                d="M364.302083 465.602819L687.954365 218.588294c38.416414-29.327534 93.791393-1.929039 93.791392 46.396277v494.029051c0 48.325316-55.374979 75.725617-93.791392 46.398084L364.302083 558.397181c-30.600916-23.357989-30.600916-69.436372 0-92.794362zM238.945254 780.798397V451.684117v-164.562559c0-19.628152-5.904521-60.475733 17.057907-75.841215 25.523642-17.068744 59.747828 1.210165 59.747828 31.919454v493.676839c0 19.628152 5.915358 60.473927-17.047069 75.841215-25.53448 17.068744-59.758666-1.211971-59.758666-31.919454z"
                fill="#cdcdcd" p-id="4593"></path>
            </svg>
            <!-- 暂停播放 -->
            <svg @click="togglePlay()" v-show="!audioStore.isPlay" t="1731744364205" class="icon"
              viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4287" width="200"
              height="200">
              <path
                d="M512 0C230.4 0 0 230.4 0 512s230.4 512 512 512 512-230.4 512-512S793.6 0 512 0z m0 981.333333C253.866667 981.333333 42.666667 770.133333 42.666667 512S253.866667 42.666667 512 42.666667s469.333333 211.2 469.333333 469.333333-211.2 469.333333-469.333333 469.333333z"
                fill="#cdcdcd" p-id="4288"></path>
              <path
                d="M672 441.6l-170.666667-113.066667c-57.6-38.4-106.666667-12.8-106.666666 57.6v256c0 70.4 46.933333 96 106.666666 57.6l170.666667-113.066666c57.6-42.666667 57.6-106.666667 0-145.066667z"
                fill="#cdcdcd" p-id="4289"></path>
            </svg>
            <svg @click="togglePlay()" v-show="audioStore.isPlay" t="1731744395735" class="icon" viewBox="0 0 1048 1024"
              version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5332" width="200" height="200">
              <path
                d="M524.272128 0.018022C241.513165 0.018022 12.288102 229.245952 12.288102 512.005018c0 112.734003 36.43904 216.957952 98.17897 301.537997l38.667981-40.258048C97.458176 699.230003 67.143168 609.158963 67.143168 512.005018 67.143168 259.540992 271.807078 54.872986 524.272128 54.872986c252.45696 0 457.120973 204.668006 457.120973 457.132032 0 252.460954-204.664013 457.118003-457.120973 457.118003-96.240026 0-185.530982-29.744026-259.189043-80.53504l-34.539008 42.797978c83.150029 58.344038 184.437965 92.596019 293.728973 92.596019 282.758963 0 511.984026-229.220966 511.984026-511.976038C1036.256154 229.245952 807.031091 0.018022 524.272128 0.018022zM615.693107 256.011981l0 511.987 54.855 0L670.548107 256.012 615.693128 256.012zM377.996083 256.011981l0 511.987 54.855 0L432.851083 256.012 377.996128 256.012z"
                p-id="5333" fill="#cdcdcd"></path>
            </svg>
            <!-- 下一首 -->
            <svg @click="next()" t="1731744740760" class="icon" viewBox="0 0 1024 1024" version="1.1"
              xmlns="http://www.w3.org/2000/svg" p-id="6865" width="200" height="200">
              <path
                d="M655.706179 465.602819L332.053897 218.588294c-38.414608-29.327534-93.791393-1.929039-93.791392 46.396277v494.029051c0 48.325316 55.376785 75.725617 93.791392 46.398084l323.652282-247.014525c30.602722-23.357989 30.602722-69.436372 0-92.794362zM781.064814 780.798397V451.684117v-164.562559c0-19.628152 5.904521-60.475733-17.057907-75.841215-25.523642-17.068744-59.747828 1.210165-59.747828 31.919454v493.676839c0 19.628152-5.915358 60.473927 17.047069 75.841215 25.532673 17.068744 59.758666-1.211971 59.758666-31.919454z"
                fill="#cdcdcd" p-id="6866"></path>
            </svg>
          </div>
        </div>
        <div class="right">
          <div class="lyrics-container" ref="lyricsContainerRef">
            <div v-if="!parsedLyrics.length" class="lyric-line">
              暂无歌词
            </div>

            <div v-for="(line, index) in parsedLyrics" :key="index" :class="{
              'lyric-line': true,
              'active': currentLyricIndex === index
            }" :ref="el => { if (el) lyricLineRefs[index] = el }">
              {{ line.text }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </Transition>
</template>

<script setup>
import { useAudioStore } from '@/store/audio';
import { computed, ref, onMounted, watch } from 'vue';
import { Close } from '@element-plus/icons-vue';
import config from '../../public/config';
import ColorThief from 'colorthief';
import logo3 from '@/assets/music.png';

const audioStore = useAudioStore();
const backgroundColor = ref('rgba(0, 0, 0, 0.5)');
const imgRef = ref(null);

const closeDrawer = () => {
  audioStore.isDetailShow = false;
};

const handleImageLoad = async () => {
  try {
    const img = imgRef.value;
    if (!img) return;

    // 确保图片已经完全加载
    if (!img.complete) {
      await new Promise(resolve => {
        img.onload = resolve;
      });
    }

    const colorThief = new ColorThief();
    const color = colorThief.getColor(img);
    backgroundColor.value = `rgba(${color[0]}, ${color[1]}, ${color[2]}, 0.8)`;
  } catch (error) {
    backgroundColor.value = 'rgba(0, 0, 0, 0.5)';
  }
};

// 监听图片变化
onMounted(() => {
  if (imgRef.value && imgRef.value.complete) {
    handleImageLoad();
  }
  console.log('歌词数据:', audioStore.lyric);
});

// 只需要这些变量
const currentLyricIndex = ref(0);
const lyricLineRefs = ref([]);
const lyricsContainerRef = ref(null);
const parsedLyrics = ref([]);

// 解析歌词函数
const parseLyrics = (lyricsText) => {

  // 如果是字符串，按原来的方式处理
  if (typeof lyricsText === 'string') {
    if (!lyricsText || !lyricsText.length) return [];

    const lines = lyricsText.split('\n');
    const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\](.*)/;

    return lines
      .map(line => {
        const match = timeRegex.exec(line);
        if (!match) return null;

        const minutes = parseInt(match[1]);
        const seconds = parseInt(match[2]);
        const milliseconds = parseInt(match[3]);
        const time = minutes * 60 + seconds +
          (milliseconds < 100 ? milliseconds / 100 : milliseconds / 1000);
        const text = match[4].trim();

        return { time, text };
      })
      .filter(item => item && item.text);
  }

  // 如果已经是数组格式，直接返回
  if (Array.isArray(lyricsText)) {
    return lyricsText;
  }

  return [];
};

// 监听歌词变化
watch(() => audioStore.lyric, (newLyric) => {
  parsedLyrics.value = parseLyrics(newLyric);
  currentLyricIndex.value = 0;
}, { immediate: true });

// 监听音频进度更新歌词
watch(() => audioStore.curTime, (newTime) => {
  if (!parsedLyrics.value || parsedLyrics.value.length === 0) return;

  const index = parsedLyrics.value.findIndex((line, i) => {
    const nextLine = parsedLyrics.value[i + 1];
    return line.time <= newTime && (!nextLine || nextLine.time > newTime);
  });

  if (index !== -1 && index !== currentLyricIndex.value) {
    currentLyricIndex.value = index;
    if (lyricLineRefs.value[index] && lyricsContainerRef.value) {
      // 修改滚动逻辑，确保当前歌词行居中
      const lineElement = lyricLineRefs.value[index];
      const container = lyricsContainerRef.value;
      const containerHeight = container.clientHeight;
      const lineTop = lineElement.offsetTop;
      const lineHeight = lineElement.clientHeight;

      // 计算需要滚动的位置，使当前行居中
      const scrollTop = lineTop - (containerHeight / 2) + (lineHeight / 2);

      container.scrollTo({
        top: scrollTop,
        behavior: 'smooth'
      });
    }
  }
});
function togglePlay() {
    if (audioStore.isPlay) {
        audioStore.isPlay = false
    } else {
        audioStore.isPlay = true
    }
}
// 获取下一个要播放的索引
function getNextIndex() {
  if (audioStore.playMode === 'random') {
    // 随机播放模式：生成除当前索引外的随机索引
    const currentIndex = audioStore.listIndex;
    let randomIndex;
    do {
      randomIndex = Math.floor(Math.random() * audioStore.listOfSong.length);
    } while (randomIndex === currentIndex && audioStore.listOfSong.length > 1);
    return randomIndex;
  } else {
    // 顺序播放模式
    if (audioStore.listIndex < audioStore.listOfSong.length - 1) {
      return audioStore.listIndex + 1;
    }
    return 0;
  }
}

// 获取上一个要播放的索引
function getPrevIndex() {
  if (audioStore.playMode === 'random') {
    // 随机播放模式：生成除当前索引外的随机索引
    const currentIndex = audioStore.listIndex;
    let randomIndex;
    do {
      randomIndex = Math.floor(Math.random() * audioStore.listOfSong.length);
    } while (randomIndex === currentIndex && audioStore.listOfSong.length > 1);
    return randomIndex;
  } else {
    // 顺序播放模式
    if (audioStore.listIndex > 0) {
      return audioStore.listIndex - 1;
    }
    return audioStore.listOfSong.length - 1;
  }
}

function prev() {
  if (audioStore.listIndex !== -1 && audioStore.listOfSong.length > 1) {
    audioStore.listIndex = getPrevIndex();
    toPlay(audioStore.listOfSong[audioStore.listIndex].url);
  }
}

function next() {
  if (audioStore.listIndex !== -1 && audioStore.listOfSong.length > 1) {
    audioStore.listIndex = getNextIndex();
    toPlay(audioStore.listOfSong[audioStore.listIndex].url);
  }
}
function toPlay(url) {
    if (url && url != audioStore.url) {
        audioStore.id = audioStore.listOfSong[audioStore.listIndex].id;
        audioStore.url =audioStore.listOfSong[audioStore.listIndex].url;
        audioStore.pic = audioStore.listOfSong[audioStore.listIndex].pic
        audioStore.title = audioStore.listOfSong[audioStore.listIndex].name
        audioStore.singerId = audioStore.listOfSong[audioStore.listIndex].singerId
        audioStore.lyric = audioStore.listOfSong[audioStore.listIndex].lyric
    }
}
</script>

<style scoped>
.custom-drawer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 93.5vh;
  z-index: 2000;
  backdrop-filter: blur(25px);
  border-radius: 10px;
  transition: background 0.5s ease;
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  cursor: pointer;
  z-index: 2001;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  color: white;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: rotate(90deg);
}

.main {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 93.5vh;
  text-align: center;
}

.left {
  width: 50%;
  height: 100%;
  display: flex;
  flex-direction: column;
  text-align: center;
  justify-content: center;
  padding: 20px;
}

.img-container {
  width: 350px;
  height: 350px;
  margin: 0 auto;
  border-radius: 50%;
  overflow: hidden;
}

.img-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
  transition: transform 0.3s ease;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.rotating {
  animation: rotate 20s linear infinite;
  animation-play-state: running;
}

.rotating:hover {
  transform: scale(1.05);
  animation-play-state: paused;
}

.song-title {
  font-size: 30px;
  font-weight: 800;
  margin-bottom: 10px;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.artist-name {
  font-size: 25px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.7);
}

.right {
  width: 50%;
  height: 100%;
  padding: 20px;
  padding-right: 10px;
  padding-left: 0;
}

.lyrics-container {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
  mask-image: linear-gradient(to bottom,
      transparent 0%,
      black 10%,
      black 90%,
      transparent 100%);
  color: white;
  text-align: left;
}

.lyric-line {
  font-size: 18px;
  line-height: 2.2;
  color: rgba(255, 255, 255, 0.6);
  transition: all 0.3s ease;
  padding: 8px 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.lyric-line.active {
  color: white;
  font-size: 22px;
  font-weight: bold;
}

/* 自定义滚动条样式 */
.lyrics-container::-webkit-scrollbar {
  width: 6px;
}

.lyrics-container::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.lyrics-container::-webkit-scrollbar-track {
  background-color: rgba(0, 0, 0, 0.1);
}

/* 动画效果 */
.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease-out;
}

.slide-up-enter-from {
  transform: translateY(100%);
}

.slide-up-leave-to {
  transform: translateY(100%);
}

.slide-up-enter-to,
.slide-up-leave-from {
  transform: translateY(0);
}

.control-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  margin-top: 20px;
  margin-right: 55px;
}

.control-icon {
  font-size: 28px;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.control-icon:hover {
  transform: scale(1.1);
  color: rgba(255, 255, 255, 0.8);
} 

.play-icon {
  font-size: 36px;
}

.icon {
  width: 50px;
  height: 50px;
  cursor: pointer;
}
</style>